import { Component, OnInit, Input, Output, EventEmitter, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { CommonService } from '../../../services-common/common.service';
import { SecondPriceChangeService } from './second-price-change.service';

@Component({
  selector: 'second-price-change',
  templateUrl: './second-price-change.component.html',
  styleUrls: ['./second-price-change.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => SecondPriceChangeComponent),
      multi: true
    }
  ]
})
export class SecondPriceChangeComponent implements ControlValueAccessor, OnInit {
  @Input() goodsId!: number | string;
  @Output() priceChangeOk = new EventEmitter();

  modelInfos = [
    {key: 'equipmentCode', name: '机器编码', value: ''},
    {key: 'modelName', name: '机器型号', value: ''},
    {key: 'realValuation', name: '成交入库价', value: ''},
    {key: 'checkTime', name: '成交入库时间', value: ''},
    {key: 'shopPriceB', name: 'B端售价', value: ''},
    {key: 'shelvesTime', name: '上架时间', value: ''},
    {key: 'shopPriceC', name: 'C端售价', value: ''},
    {key: 'libraryName', name: '库位', value: ''}
  ];
  formParams: any = {
    shopPriceB: '',
    shopPriceC: ''
  };
  // 利润 利润率
  profitObjs: any = {
    profitB: 0,
    profitRateB: 0,
    profitC: 0,
    profitRate: 0
  };
  deviceInfo: any = {
    realValuation: 0,
    aprc: 0,
    cprc: 0
  }
  priceChangeTable: any[] = [];
  isLoadSpinning = false;
  submitLoading = false;

  isMakeVisible = false;
  _onChange: any = () => {};

  constructor(
    private message: NzMessageService,
    private modal: NzModalService,
    private commonService: CommonService,
    private priceChangeServices: SecondPriceChangeService
  ) { }

  ngOnInit(): void {
  }

  async loadPriceChangeData() {
    let params = {
      id: this.goodsId,
      page: 1,
      pageSize: 100
    }
    this.isLoadSpinning = true;
    const res: any = await this.priceChangeServices.getPriceChangeData(params);
    this.isLoadSpinning = false;

    if (res.code === 0) {
      const {recycleGoods, goodsLogIPage} = res.data || {};
      this.modelInfos.forEach(item => {
        item.value = recycleGoods[item.key] || '';

        // 成交价 = realValuation + aprc(加价) + cprc(下单抽奖)
        if (item.key === 'realValuation') {
          item.value = (recycleGoods.realValuation || 0) + (recycleGoods.aprc || 0) + (recycleGoods.cprc || 0);
        }
      })

      for (let key in this.deviceInfo) {
        this.deviceInfo[key] = recycleGoods[key] || '';
      }

      for (let key in this.formParams) {
        this.formParams[key] = recycleGoods[key] || '';
      }
      this.profitObjs.profitB = this.sumProfit(recycleGoods.shopPriceB, 1);
      this.profitObjs.profitRateB = this.sumProfit(recycleGoods.shopPriceB, 2);
      this.profitObjs.profitC = this.sumProfit(recycleGoods.shopPriceC, 1);
      this.profitObjs.profitRateC = this.sumProfit(recycleGoods.shopPriceC, 2);
      
      this.priceChangeTable = goodsLogIPage.records || [];
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * type 1：利润 2：利润率
   * 利润：输入的值 - (输入的值 / 1.03 * 0.03) - (输入的值 / 1.03 * 0.03) * 0.12  - (输入的值 * 0.006) - 成交价 - 60
   * 利润率：利润 / (成交价 + 60 + (输入的值 / 1.03 * 0.03) * 0.12  + 输入的值 * 0.006) 1.1289
   * 注：成交价 = realValuation + aprc + cprc
   */
  sumProfit(val: any, type: number) {
    let baseVal = val || 0;
    let prifitTotal = 0;
    let prifitRate = 0;
    let transactionPrice = (this.deviceInfo?.realValuation || 0) + (this.deviceInfo?.aprc || 0) + (this.deviceInfo?.cprc || 0); // 成交价

    prifitTotal = baseVal - (baseVal / 1.03 * 0.03) - (baseVal / 1.03 * 0.03 * 0.12) - (baseVal * 0.006) - (transactionPrice || 0) - 60;
    prifitRate = prifitTotal / ((transactionPrice || 0) + 60 + (baseVal / 1.03 * 0.03 * 0.12) + (baseVal * 0.006));

    return type === 1 ? prifitTotal.toFixed(2) : (prifitRate * 100).toFixed(2);
  }

  priceChange(event: any, type: string) {
    if (type === 'b') {
      this.profitObjs.profitB = this.sumProfit(event, 1);
      this.profitObjs.profitRateB = this.sumProfit(event, 2);
    } else {
      this.profitObjs.profitC = this.sumProfit(event, 1);
      this.profitObjs.profitRateC = this.sumProfit(event, 2);
    }
  }

  subPriceChange() {
    if (this.commonService.isEmpty(this.formParams.shopPriceB)) {
      this.message.warning('请输入B端价格');
      return
    } else if (this.commonService.isEmpty(this.formParams.shopPriceC)) {
      this.message.warning('请输入C端价格');
      return
    }
    
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确认操作?',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          id: this.goodsId,
          ...this.formParams
        }
        this.submitLoading = true;
        const res: any = await this.priceChangeServices.updatePriceData(params);
        this.submitLoading = false;

        if (res.code === 0) {
          this.message.success('操作成功');
          this.handleCancel();
          this.priceChangeOk.emit();
        } else {
          this.message.error(res.message);
        }
      },
      nzCancelText: '取消'
    });
  }

  getDiffValue(newVal: any, oldVal: any) {
    return (newVal || 0) - (oldVal || 0);
  }

  getTimesAgo(time: string) {
    let tiamAgo = 0;
    tiamAgo = (Date.now() - +new Date(time)) / (1000 * 60 * 60 * 24);
    console.log('tiame ago', tiamAgo);
    return tiamAgo ? Math.floor(tiamAgo) : 0;
  }

  /**
   * ngModel
   * ----------------------------------------------------------------
   */
  handleCancel() {
    this.isMakeVisible = false;
    this._onChange(false);
  }

  writeValue(val: any) {
    if (val) {
      for (let key in this.formParams) {
        this.formParams[key] = '';
      }
      this.loadPriceChangeData();
    }
    this.isMakeVisible = val;
  }

  registerOnChange(fn: (_: any) => void): void {
    this._onChange = fn;
  }

  registerOnTouched(fn: any): void {}
}
